package net.xdclass.service.impl;

import lombok.extern.slf4j.Slf4j;
import lombok.val;
import net.xdclass.config.RabbitMQConfig;
import net.xdclass.controller.request.AccountLoginRequest;
import net.xdclass.controller.request.AccountRegisterRequest;
import net.xdclass.enums.AuthTypeEnum;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.enums.EventMessageType;
import net.xdclass.enums.SendCodeEnum;
import net.xdclass.interceptor.LoginInterceptor;
import net.xdclass.manager.AccountManger;
import net.xdclass.model.AccountDO;
import net.xdclass.model.EventMessage;
import net.xdclass.model.LoginUser;
import net.xdclass.service.AccountService;
import net.xdclass.service.NotifyService;
import net.xdclass.util.*;
import net.xdclass.vo.AccountVO;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 功能描述
 *
 * @author ASUS
 * @date 2024/07/02  17:30
 */
@Service
@Slf4j
public class AccountServiceImpl implements AccountService {
    /**
     * 免费流ᰁ包ID
     */
    private static final Long FREE_TRAFFIC_PRODUCT_ID = 1L;
    @Autowired
    private NotifyService notifyService;
    @Autowired
    private AccountManger accountManger;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RabbitMQConfig rabbitMQConfig;
    @Override
    public JsonData register(AccountRegisterRequest request) {
        boolean checkCode = false;
        //校验验证码
        String phone = request.getPhone();
        if(StringUtils.isNotBlank(phone)) {
            checkCode = notifyService.checkCode(SendCodeEnum.USER_REGISTER, phone, request.getCode());
        }
        //验证码错误
        if(!checkCode){
            return JsonData.buildResult(BizCodeEnum.CODE_TO_ERROR);
        }
        AccountDO accountDO = new AccountDO();
        BeanUtils.copyProperties(request,accountDO);
        //认证级别
        accountDO.setAuth(AuthTypeEnum.DEFAULT.name());
        // 生成唯一的账户id
//        accountDO.setAccountNo(CommonUtil.getCurrentTimestamp());
        accountDO.setAccountNo(Long.valueOf(IDUtil.geneSnowFlakeID().toString()));
        //设置密码 私钥 盐
        accountDO.setSecret("$1$"+ CommonUtil.getStringNumRandom(8));
        //设置加密后的密码
        String cryptPwd = Md5Crypt.md5Crypt(request.getPwd().getBytes(), accountDO.getSecret());
        accountDO.setPwd(cryptPwd);

//        密码加密

//        账号唯⼀性检查(TODO)
//        插⼊数据库
        int rows = accountManger.insert(accountDO);
        log.info("rows:{}  插入成功:{}",rows,accountDO);
//        新注册⽤户福利发放
        userRegisterInitTask(accountDO);
        return JsonData.buildSuccess();

    }

    @Override
    public JsonData login(AccountLoginRequest request) {
            List<AccountDO> accountDOList = accountManger.findByPhone(request.getPhone());
            if(accountDOList!=null && accountDOList.size() == 1){
                AccountDO accountDO = accountDOList.get(0);
                String secret = accountDO.getSecret();
                String md5Crypt = Md5Crypt.md5Crypt(request.getPwd().getBytes(), secret);
                if(md5Crypt.equalsIgnoreCase(accountDO.getPwd())){
                    LoginUser loginUser = LoginUser.builder().build();
                    BeanUtils.copyProperties(accountDO,loginUser);
                    //生成token
                    String token = JWTUtil.geneJsonWebTokne(loginUser);
                    return JsonData.buildSuccess(token);
                }else{
                    return JsonData.buildResult(BizCodeEnum.ACCOUNT_PWD_ERROR);
                }
            }else{
                return JsonData.buildResult(BizCodeEnum.ACCOUNT_UNREGISTER);
            }

    }

    @Override
    public JsonData detail() {
        Long accountNo = LoginInterceptor.threadLocal.get().getAccountNo();
        AccountDO accountDO = accountManger.detail(accountNo);
        if(Objects.nonNull(accountDO)){
            AccountVO accountVO = new AccountVO();
            BeanUtils.copyProperties(accountDO,accountVO);
            return JsonData.buildSuccess(accountVO);
        }else {
            return JsonData.buildError(BizCodeEnum.ACCOUNT_PWD_ERROR.name());
        }

    }

    /**
     * 用户注册，初始化福利信息
     * 注册成功后在发送
     * (消费前查询下是否有这个⽤户,⾮必要)
     * @param accountDO
     */
    private void userRegisterInitTask(AccountDO accountDO) {
        EventMessage message = EventMessage.builder().messageId(IDUtil.geneSnowFlakeID().toString())
                .accountNo(accountDO.getAccountNo())
                .eventMessageType(EventMessageType.TRAFFIC_FREE_INIT.name())
                .bizId(FREE_TRAFFIC_PRODUCT_ID.toString())
                .build();
        rabbitTemplate.convertAndSend(rabbitMQConfig.getTrafficEventExchange(),
                rabbitMQConfig.getTrafficFreeInitRoutingKey(),message);

    }

}
